<template>
    <div class="exam-detail">
      <div class="page-header">
        <h1>考试详情</h1>
        <div class="header-actions">
          <el-button type="primary" @click="handleEdit">
            <el-icon><Edit /></el-icon>
            编辑考试
          </el-button>
          <el-button type="success" @click="$router.push(`/questions?exam_id=${exam.id}`)">
            <el-icon><List /></el-icon>
            管理题目
          </el-button>
          <el-button 
            v-if="exam.status === 'draft'" 
            type="warning" 
            @click="handlePublish"
          >
            <el-icon><Upload /></el-icon>
            发布考试
          </el-button>
          <el-button 
            v-if="exam.status === 'published'" 
            type="danger" 
            @click="handleUnpublish"
          >
            <el-icon><Download /></el-icon>
            取消发布
          </el-button>
          <el-button type="danger" @click="handleDelete">
            <el-icon><Delete /></el-icon>
            删除考试
          </el-button>
        </div>
      </div>

      <el-row :gutter="20">
        <el-col :span="16">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>基本信息</span>
              </div>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="考试名称">{{ exam.title }}</el-descriptions-item>
              <el-descriptions-item label="考试类型">
                <el-tag :type="getExamTypeType(exam.exam_type)">
                  {{ getExamTypeText(exam.exam_type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="考试状态">
                <el-tag :type="getStatusType(exam.status)">
                  {{ getStatusText(exam.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="题目数量">{{ exam.question_count || 0 }}</el-descriptions-item>
              <el-descriptions-item label="考试时长">{{ exam.duration }} 分钟</el-descriptions-item>
              <el-descriptions-item label="总分">{{ exam.total_score }}</el-descriptions-item>
              <el-descriptions-item label="及格分">{{ exam.pass_score }}</el-descriptions-item>
              <el-descriptions-item label="创建者">{{ exam.creator?.full_name }}</el-descriptions-item>
              <el-descriptions-item label="开始时间">{{ formatDateTime(exam.start_time) }}</el-descriptions-item>
              <el-descriptions-item label="结束时间">{{ formatDateTime(exam.end_time) }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDateTime(exam.created_at) }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ formatDateTime(exam.updated_at) }}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <el-card style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <span>考试描述</span>
              </div>
            </template>
            <div class="exam-description">
              {{ exam.description || '暂无描述' }}
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>快捷操作</span>
              </div>
            </template>
            <div class="quick-actions">
              <el-button 
                type="primary" 
                size="large" 
                @click="$router.push(`/questions?exam_id=${exam.id}`)"
                style="width: 100%; margin-bottom: 10px;"
              >
                <el-icon><List /></el-icon>
                管理题目
              </el-button>
              <el-button 
                type="success" 
                size="large" 
                @click="$router.push(`/scores?exam_id=${exam.id}`)"
                style="width: 100%; margin-bottom: 10px;"
              >
                <el-icon><DataLine /></el-icon>
                查看成绩
              </el-button>
              <el-button 
                type="info" 
                size="large" 
                @click="handlePreview"
                style="width: 100%;"
              >
                <el-icon><View /></el-icon>
                预览考试
              </el-button>
            </div>
          </el-card>

          <el-card style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <span>考试统计</span>
              </div>
            </template>
            <div class="exam-stats">
              <div class="stat-item">
                <div class="stat-label">题目总数</div>
                <div class="stat-value">{{ exam.question_count || 0 }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">平均分值</div>
                <div class="stat-value">{{ exam.question_count ? Math.round(exam.total_score / exam.question_count) : 0 }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">及格率</div>
                <div class="stat-value">{{ exam.pass_score }}%</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import api from '../api';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Edit, List, DataLine, View, Upload, Download, Delete } from '@element-plus/icons-vue';
  
  const route = useRoute();
  const router = useRouter();
  const exam = ref({});
  
  const formatDateTime = (datetime) => {
    return new Date(datetime).toLocaleString('zh-CN');
  };
  
  const getStatusType = (status) => {
    const statusMap = {
      'draft': 'info',
      'published': 'success',
      'ongoing': 'warning',
      'completed': 'danger'
    };
    return statusMap[status] || 'info';
  };
  
  const getStatusText = (status) => {
    const statusMap = {
      'draft': '草稿',
      'published': '已发布',
      'ongoing': '进行中',
      'completed': '已完成'
    };
    return statusMap[status] || '未知';
  };
  
  const getExamTypeType = (type) => {
    const typeMap = {
      'formal': 'danger',
      'practice': 'success'
    };
    return typeMap[type] || 'info';
  };
  
  const getExamTypeText = (type) => {
    const typeMap = {
      'formal': '正式考试',
      'practice': '练习考试'
    };
    return typeMap[type] || '未知';
  };
  
  const loadExam = async () => {
    try {
      const response = await api.exams.getExamDetail(route.params.id);
      exam.value = response.data;
    } catch (error) {
      ElMessage.error('加载考试详情失败');
    }
  };
  
  const handleEdit = () => {
    ElMessage.info('编辑功能开发中...');
  };
  
  const handlePublish = async () => {
    try {
      await ElMessageBox.confirm(
        `确定要发布考试"${exam.value.title}"吗？发布后学生将能看到此考试。`,
        '发布确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      
      await api.exams.updateExam(exam.value.id, { status: 'published' });
      ElMessage.success('考试发布成功');
      loadExam();
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('发布考试失败');
      }
    }
  };
  
  const handleUnpublish = async () => {
    try {
      await ElMessageBox.confirm(
        `确定要取消发布考试"${exam.value.title}"吗？取消后学生将无法看到此考试。`,
        '取消发布确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      
      await api.exams.updateExam(exam.value.id, { status: 'draft' });
      ElMessage.success('考试取消发布成功');
      loadExam();
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('取消发布考试失败');
      }
    }
  };
  
  const handleDelete = async () => {
    try {
      await ElMessageBox.confirm(
        `确定要删除考试"${exam.value.title}"吗？此操作不可恢复。`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      
      await api.exams.deleteExam(exam.value.id);
      ElMessage.success('考试删除成功');
      router.push('/exams');
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除考试失败');
      }
    }
  };
  
  const handlePreview = () => {
    ElMessage.info('预览功能开发中...');
  };
  
  onMounted(() => {
    loadExam();
  });
  </script>
  
  <style scoped>
  .exam-detail {
    padding: 20px;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .page-header h1 {
    margin: 0;
    font-size: 24px;
    color: #303133;
  }
  
  .header-actions {
    display: flex;
    gap: 10px;
  }
  
  .card-header {
    font-size: 18px;
    font-weight: bold;
  }
  
  .exam-description {
    line-height: 1.6;
    color: #606266;
  }
  
  .quick-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .exam-stats {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .stat-item:last-child {
    border-bottom: none;
  }
  
  .stat-label {
    font-size: 14px;
    color: #909399;
  }
  
  .stat-value {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
  }
  </style>